import datetime
import os
import sys
import io

configFileName = './config.ini'


def getVal(filename, attrib):
    open(filename,'a').close()
    for line in reversed(open(filename,'r').readlines()):
        if len(line) == 0 :
            continue
        line = line.split("#")[0].split("//")[0]  #on vire les commentaires
        pair = line.split("=")
        if len(pair) == 2: #c'est bien une declaration de valeur
            atr,val = pair[0].strip(),pair[1].strip()
            #check si c'est une ligne de version
            if atr == attrib:
                print("attrib "+atr+" found := "+val)
                return True,val
    print('attribut '+attrib+' not found in '+filename)
    return False,'not found'

# read config file

success2,headerFileName = getVal(configFileName,'headerVersionFileName')
success,historyFileName = getVal(configFileName,'historyVersionFileName')


#check history
Maj,Min,Build = 0,0,0
if success :
    success,version = getVal(historyFileName,'version')
    if success:
        v,Build=version.split(':')
        Maj,Min = v.split('.')
        
print(Maj,Min,Build)


#update du "history.txt"
Maj= int(Maj)
Min= int(Min)
Build= int(Build)
tag=" "

if len(sys.argv) >= 2 :
    if sys.argv[1] == "bld" :
        Build += 1
    if sys.argv[1] == "min" :
        Build = 0
        Min += 1
    if sys.argv[1] == "maj" :
        Build = 0
        Min = 0
        Maj += 1

if len(sys.argv) >= 3 :
    if sys.argv[2] == "alpha" :
        tag="a"
    if sys.argv[2] == "beta" :
        tag="b"
        

vf = open(historyFileName, 'a')
now=str(datetime.date.today())
now += ' @ ' + str(datetime.datetime.now()).split('.')[0].split(" ")[1]

if Maj+Min+Build==0:#fresh history file
    vf.write('# VERSION HISTORY')

vf.write("\nversion = "+str(Maj)+"."+str(Min)+":"+str(Build)+"\t# build date: "+now)
vf.close()


#creation du "version.h"
vf=open(headerFileName,'w')

vf.write("#pragma once"+'\n'+'\n')
vf.write("/******************************"+'\n')
vf.write("* version.h                   *"+'\n')
vf.write("* date: "+now+              ' *'+'\n')
vf.write("*******************************"+'\n')
vf.write("* THIS FILE IS AUTOMATICALY   *"+'\n')
vf.write("* GENERATED. ANY MODIFICATION *"+'\n')
vf.write("* WILL BE LOST AT NEXT GEN.   *"+'\n')
vf.write("******************************/"+'\n'+'\n')

vf.write("#define MAJOR_VERSION "+str(Maj)+'\n')
vf.write("#define MINOR_VERSION "+str(Min)+'\n')
vf.write("#define BUILD_VERSION "+str(Build)+'\n'+'\n')
vf.write("#define BUILD_DATE \""+now+'\"'+'\n')
vf.write("#define TEXT_VERSION \"v"+str(Maj)+'.'+str(Min)+':'+str(Build)+'\"'+'\n')
vf.close()
#print("version="+str(Maj)+"."+str(Min)+":"+str(Build)+"\t# build date: "+str(now))





